package com.xyzq.cgate.core.handler;

import com.xyzq.cgate.common.response.ResponseEntity;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @Description:
 * @author chenchen
 * @date 2019/6/21 9:49
 */
public class GlobalErrorWebExceptionHandler extends DefaultErrorWebExceptionHandler {

    public GlobalErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    @Override
    protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
        Throwable error = super.getError(request);
        error.printStackTrace();
        String errorMessage = error.getMessage();
        ResponseEntity errorEntity = new ResponseEntity().failure(errorMessage);
        HttpStatus errorStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        return ServerResponse.status(errorStatus)
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .body(BodyInserters.fromObject(errorEntity))
                    .doOnNext((resp) -> {
            this.logError(request, errorStatus);
        });
    }
}
